package com.heakey.common.config.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.heakey.common.config.InterceptorConfig;
import com.heakey.common.constant.CommonConstant;
import com.heakey.common.enums.BaseErrorCodeEnum;
import com.heakey.common.iface.IUserAuthService;
import com.heakey.common.model.Result;
import com.heakey.common.properties.InterceptorProperties;
import com.heakey.common.util.context.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

/**
 * @Description Front拦截器
 * @Author Bing
 * @Date 2024/10/14 16:15
 */
@Slf4j
@Component
@ConditionalOnClass(InterceptorConfig.class)
public class FrontInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserAuthService userAuthService;

    @Autowired(required = false)
    private InterceptorProperties interceptorProperties;

    /**
     * 业务ID
     */
    private static final String BIZ_ID = "bizId";

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 白名单
        if(ObjectUtil.isNotNull(interceptorProperties) && ObjectUtil.isNotNull(interceptorProperties.getUrlWhitelist())){
            // 匹配白名单
            Optional<String> optional = Arrays.stream(interceptorProperties.getUrlWhitelist()).filter(url -> {
                return antPathMatcher.match(url, request.getRequestURI());
            }).findFirst();
            if(optional.isPresent()){
                // 不强制登录也设置用户上下文
                noForceLogin(request);
                return true;
            }
        }
        // 获取token
        String token = request.getHeader(CommonConstant.TOKEN_HEADER);
        if(StrUtil.isBlank(token)){
            writeJson(response, Result.error(BaseErrorCodeEnum.NOT_ACCEPTABLE));
            log.info("{}:用户未登录:{}", token,request.getRequestURI());
            return false;
        }
        // 验证token
        Long userId = userAuthService.isLogin(token,true);
        if(userId <= 0){
            writeJson(response,Result.error(BaseErrorCodeEnum.UNAUTHORIZED));
            log.info("{}:用户未登录:{}", token,request.getRequestURI());
            return false;
        }
        MDC.put(BIZ_ID,userId.toString());
        UserContextHolder.setUserId(userId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserContextHolder.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.remove();
    }

    private void writeJson(HttpServletResponse response, Result result) throws Exception {
        renderString(response, JSON.toJSONString(result));
    }

    private static void renderString(HttpServletResponse response, String string)
    {
        try
        {
            response.setStatus(CommonConstant.DEFAULT_SUCCESS_CODE);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            log.error("renderString error", e);
        }
    }

    /**
     * 非强制登录
     * @param request
     */
    private void noForceLogin(HttpServletRequest request){
        try {
            // 获取token
            String token = request.getHeader(CommonConstant.TOKEN_HEADER);
            if(StrUtil.isBlank(token)){
                return;
            }
            // 验证token
            Long userId = userAuthService.isLogin(token, false);
            if(ObjectUtil.isNull(userId)){
                return;
            }
            if(userId <= CommonConstant.NUM_ZERO){
                return;
            }
            MDC.put(BIZ_ID,userId.toString());
            UserContextHolder.setUserId(userId);
        }catch (Exception e){

        }
    }
}